/*******************************************************************************
 * Package: com.song.boot.springstudy.netty.simple
 * Type:    NettyServer
 * Date:    2023-06-04 17:38
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.chat.selfish;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 功能描述： 服务器
 *
 * @author Songxianyang
 * @date 2023-06-04 17:38
 */
public class ChartNettyServer {
    private Integer port;

    public ChartNettyServer(Integer port) {
        this.port = port;
    }

    public void run() throws Exception {

        EventLoopGroup bossEvent = new NioEventLoopGroup();
        EventLoopGroup workerEvent = new NioEventLoopGroup();

        try {
            // 服务器端 配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEvent,workerEvent) // 设置两个线程组
                    .channel(NioServerSocketChannel.class) // nio实现类通道
                    .option(ChannelOption.SO_BACKLOG,128) // 设置线程队列
                    .childHandler(new ChannelInitializer<SocketChannel>() {  // 创建一个通道初始化对象（匿名对象）
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("解码器", new StringDecoder());
                            pipeline.addLast("编码器", new StringEncoder());
                            pipeline.addLast(new ChartNettyServerHandler());// 向管道追加一个处理器
                        }
                    });// 给workerGroup的EventLoop对应的管道设置处理器
            System.out.println("服务器端启动完成！");
            ChannelFuture cf = serverBootstrap.bind(port).sync(); // 绑定端口，并且同步，生成了一个ChannelFuture对象

            // 注册监听器 到 ChannelFuture。从而获取 异步回调
            cf.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("监听成功：：：》》》》port:"+port);
                }else {
                    System.out.println("监听失败");
                }
            });

            cf.channel().closeFuture().sync(); // 对关闭通道进行见监听
        } finally {
            bossEvent.shutdownGracefully();  // 关闭
            workerEvent.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        ChartNettyServer chartNettyServer = new ChartNettyServer(7000);
        chartNettyServer.run();
    }
}
